// 工单管理页面JavaScript
class WorkOrdersApp {
    constructor() {
        this.baseURL = '';
        this.currentPage = 1;
        this.pageSize = 10;
        this.totalPages = 0;
        this.totalItems = 0;
        this.currentWorkOrders = [];
        this.selectedWorkOrders = new Set();
        this.currentFilters = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.updateCurrentTime();
        this.loadWorkOrders();
        this.loadProducts(); // Load products for dropdowns
        
        // Update time every second
        setInterval(() => this.updateCurrentTime(), 1000);
    }

    bindEvents() {
        // Search event
        const searchInput = document.getElementById('workOrderSearch');
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchWorkOrders();
                }
            });
        }

        // Filter events
        const statusFilter = document.getElementById('statusFilter');
        if (statusFilter) {
            statusFilter.addEventListener('change', () => this.applyFilters());
        }

        const productionLineFilter = document.getElementById('productionLineFilter');
        if (productionLineFilter) {
            productionLineFilter.addEventListener('change', () => this.applyFilters());
        }

        // Form submit events
        const workOrderForm = document.getElementById('workOrderForm');
        if (workOrderForm) {
            workOrderForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveWorkOrder(new FormData(e.target));
            });
        }

        const statusChangeForm = document.getElementById('statusChangeForm');
        if (statusChangeForm) {
            statusChangeForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.changeWorkOrderStatus(new FormData(e.target));
            });
        }
    }

    updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN');
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    // API call function
    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, {
                headers: { 'Content-Type': 'application/json', ...options.headers },
                ...options
            });
            
            const data = await response.json();
            if (!response.ok) throw new Error(data.message || `HTTP error! status: ${response.status}`);
            return data;
        } catch (error) {
            console.error('API call failed:', error);
            this.showToast(`Request failed: ${error.message}`, 'error');
            throw error;
        }
    }

    // Load work orders
    async loadWorkOrders() {
        try {
            const response = await this.apiCall('/api/workorders');
            this.currentWorkOrders = response.data || [];
            this.totalItems = this.currentWorkOrders.length;
            this.totalPages = Math.ceil(this.totalItems / this.pageSize);
            
            this.renderWorkOrdersTable();
            this.updatePagination();
            this.updateStatistics();
        } catch (error) {
            console.error('Failed to load work orders:', error);
            document.getElementById('workOrdersTableBody').innerHTML = 
                '<tr><td colspan="11" class="error">Failed to load work order data</td></tr>';
        }
    }

    // Load products for dropdown
    async loadProducts() {
        try {
            const response = await this.apiCall('/api/products');
            const products = response.data || [];
            
            // Update product filter dropdown
            const productFilter = document.getElementById('productFilter');
            if (productFilter) {
                productFilter.innerHTML = '<option value="">All Products</option>' +
                    products.map(p => `<option value="${p.id}">${p.productName} (${p.productCode})</option>`).join('');
            }

            // Update form dropdown
            const formProductSelect = document.querySelector('#workOrderForm select[name="productId"]');
            if (formProductSelect) {
                formProductSelect.innerHTML = '<option value="">Select Product</option>' +
                    products.map(p => `<option value="${p.id}">${p.productName} (${p.productCode})</option>`).join('');
            }
        } catch (error) {
            console.error('Failed to load products:', error);
        }
    }

    // Render work orders table
    renderWorkOrdersTable() {
        const tbody = document.getElementById('workOrdersTableBody');
        
        if (this.currentWorkOrders.length === 0) {
            tbody.innerHTML = '<tr><td colspan="11" class="no-data">No work order data</td></tr>';
            return;
        }

        // Pagination
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageWorkOrders = this.currentWorkOrders.slice(startIndex, endIndex);

        const rows = pageWorkOrders.map(order => {
            const isSelected = this.selectedWorkOrders.has(order.id);
            const statusBadge = this.getStatusBadge(order.status);
            const progress = this.calculateProgress(order);
            
            return `
                <tr ${isSelected ? 'class="selected"' : ''}>
                    <td>
                        <input type="checkbox" value="${order.id}" 
                               ${isSelected ? 'checked' : ''} 
                               onchange="app.toggleWorkOrderSelection(${order.id})">
                    </td>
                    <td>
                        <a href="#" onclick="app.showWorkOrderDetail(${order.id})" class="order-link">
                            ${order.orderCode || '-'}
                        </a>
                    </td>
                    <td>${order.product?.productName || '-'}</td>
                    <td>${order.plannedQuantity || 0}</td>
                    <td>${order.completedQuantity || 0}</td>
                    <td>${order.rejectedQuantity || 0}</td>
                    <td>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${progress}%"></div>
                            <span class="progress-text">${progress}%</span>
                        </div>
                    </td>
                    <td>${statusBadge}</td>
                    <td>${order.productionLine || '-'}</td>
                    <td>${this.formatDate(order.plannedStartTime)}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-primary" onclick="app.editWorkOrder(${order.id})" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-warning" onclick="app.showStatusChangeModal(${order.id})" title="Change Status">
                                <i class="fas fa-sync"></i>
                            </button>
                            <button class="btn btn-sm btn-info" onclick="app.showWorkOrderDetail(${order.id})" title="Details">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="app.deleteWorkOrder(${order.id})" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');

        tbody.innerHTML = rows;
    }

    // Get status badge
    getStatusBadge(status) {
        const statusMap = {
            'PENDING': '<span class="status-badge status-pending">Pending</span>',
            'IN_PROGRESS': '<span class="status-badge status-in-progress">In Progress</span>',
            'COMPLETED': '<span class="status-badge status-completed">Completed</span>',
            'CANCELLED': '<span class="status-badge status-cancelled">Cancelled</span>'
        };
        return statusMap[status] || '<span class="status-badge status-unknown">Unknown</span>';
    }

    // Calculate progress
    calculateProgress(order) {
        if (!order.plannedQuantity || order.plannedQuantity === 0) return 0;
        const completed = order.completedQuantity || 0;
        return Math.min(Math.round((completed / order.plannedQuantity) * 100), 100);
    }

    // Update statistics
    updateStatistics() {
        const pending = this.currentWorkOrders.filter(o => o.status === 'PENDING').length;
        const inProgress = this.currentWorkOrders.filter(o => o.status === 'IN_PROGRESS').length;
        const completed = this.currentWorkOrders.filter(o => o.status === 'COMPLETED').length;
        const cancelled = this.currentWorkOrders.filter(o => o.status === 'CANCELLED').length;

        document.getElementById('pendingCount').textContent = pending;
        document.getElementById('inProgressCount').textContent = inProgress;
        document.getElementById('completedCount').textContent = completed;
        document.getElementById('cancelledCount').textContent = cancelled;
    }

    // Show add work order modal
    showAddWorkOrderModal() {
        document.getElementById('modalTitle').textContent = 'Create Work Order';
        document.getElementById('workOrderForm').reset();
        
        // Set default planned start time to now
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        document.querySelector('input[name="plannedStartTime"]').value = now.toISOString().slice(0, 16);
        
        this.showModal();
    }

    // Save work order
    async saveWorkOrder(formData) {
        try {
            const workOrderData = Object.fromEntries(formData);
            const form = document.getElementById('workOrderForm');
            const workOrderId = form.dataset.workOrderId;

            let response;
            if (workOrderId) {
                // Update work order
                response = await this.apiCall(`/api/workorders/${workOrderId}`, {
                    method: 'PUT',
                    body: JSON.stringify(workOrderData)
                });
                this.showToast('Work order updated successfully', 'success');
            } else {
                // Add work order
                response = await this.apiCall('/api/workorders', {
                    method: 'POST',
                    body: JSON.stringify(workOrderData)
                });
                this.showToast('Work order created successfully', 'success');
            }

            this.hideModal();
            this.loadWorkOrders();
            
        } catch (error) {
            console.error('Failed to save work order:', error);
        }
    }

    // Delete work order
    async deleteWorkOrder(workOrderId) {
        if (!confirm('Are you sure you want to delete this work order? This action cannot be undone.')) {
            return;
        }

        try {
            await this.apiCall(`/api/workorders/${workOrderId}`, {
                method: 'DELETE'
            });

            this.showToast('Work order deleted successfully', 'success');
            this.selectedWorkOrders.delete(workOrderId);
            this.loadWorkOrders();
            
        } catch (error) {
            console.error('Failed to delete work order:', error);
        }
    }

    // Utility functions
    formatDate(dateString) {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleString('zh-CN');
    }

    showModal() {
        document.getElementById('workOrderModal').classList.add('show');
    }

    hideModal() {
        document.getElementById('workOrderModal').classList.remove('show');
        document.getElementById('workOrderForm').reset();
        delete document.getElementById('workOrderForm').dataset.workOrderId;
    }

    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast ${type}`;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // Selection functions
    toggleWorkOrderSelection(workOrderId) {
        if (this.selectedWorkOrders.has(workOrderId)) {
            this.selectedWorkOrders.delete(workOrderId);
        } else {
            this.selectedWorkOrders.add(workOrderId);
        }
        this.renderWorkOrdersTable();
    }

    // Pagination functions
    updatePagination() {
        document.getElementById('pageStart').textContent = 
            this.currentWorkOrders.length > 0 ? (this.currentPage - 1) * this.pageSize + 1 : 0;
        document.getElementById('pageEnd').textContent = 
            Math.min(this.currentPage * this.pageSize, this.totalItems);
        document.getElementById('totalItems').textContent = this.totalItems;

        document.getElementById('prevBtn').disabled = this.currentPage <= 1;
        document.getElementById('nextBtn').disabled = this.currentPage >= this.totalPages;

        this.generatePageNumbers();
    }

    generatePageNumbers() {
        const pageNumbers = document.getElementById('pageNumbers');
        let html = '';

        const maxVisiblePages = 5;
        let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

        for (let i = startPage; i <= endPage; i++) {
            html += `
                <button class="btn btn-sm ${i === this.currentPage ? 'btn-primary' : 'btn-secondary'}" 
                        onclick="app.goToPage(${i})">${i}</button>
            `;
        }

        pageNumbers.innerHTML = html;
    }

    goToPage(page) {
        if (page >= 1 && page <= this.totalPages) {
            this.currentPage = page;
            this.renderWorkOrdersTable();
            this.updatePagination();
        }
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.goToPage(this.currentPage - 1);
        }
    }

    nextPage() {
        if (this.currentPage < this.totalPages) {
            this.goToPage(this.currentPage + 1);
        }
    }
}

// Global functions
function showAddWorkOrderModal() {
    window.app.showAddWorkOrderModal();
}

function searchWorkOrders() {
    if (window.app) {
        window.app.showToast('Search function under development...', 'info');
    }
}

function clearFilters() {
    if (window.app) {
        window.app.showToast('Clear filters function under development...', 'info');
    }
}

function hideModal() {
    window.app.hideModal();
}

function toggleSelectAll() {
    if (window.app) {
        window.app.showToast('Select all function under development...', 'info');
    }
}

function exportWorkOrders() {
    if (window.app) {
        window.app.showToast('Export function under development...', 'info');
    }
}

function sortTable(column) {
    if (window.app) {
        window.app.showToast('Sort function under development...', 'info');
    }
}

function previousPage() {
    window.app.previousPage();
}

function nextPage() {
    window.app.nextPage();
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    window.app = new WorkOrdersApp();
});